package com.mis.geoEncryption.model.xml;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.transform.Source;

public class XMLProcessor implements IXMLProcessor {
	
	public String processXMLMessage(String msg) {
		Object obj = createObjectModelFromXML(msg);
		String returnMessage = generateMessage(obj);
		
		return returnMessage;
	}
	
	public Object createObjectModelFromXML(String xml) {
		XMLToObjectFactory factory = XMLToObjectFactory.getXMLToObjectFactoryInstance();
		Object recievedObject = factory.convertToObject(xml);
		return recievedObject;
	}
	
	public String generateMessage(Object obj) {
		MessageFactory messagFac = MessageFactory.getMessageFactoryInstance();
		messagFac.generateMessage(obj);
		String xmlString = convertToXML(obj, obj.getClass());
		
		return xmlString;
	}
	
	 private String convertToXML(Object source, Class type) {
	        String result;
	        StringWriter witer = new StringWriter();
	        try {
	            JAXBContext jxbContext = JAXBContext.newInstance(type);
	            Marshaller jxbMarshaller = jxbContext.createMarshaller();
	            jxbMarshaller.marshal(source, witer);
	            result = witer.toString();
	        } catch (JAXBException e) {
	        	e.printStackTrace();
	            throw new RuntimeException(e);
	        }

	        return result;
	    }

}
